package com.jd.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jd.basic.constant.PhoneRegisterCons;
import com.jd.basic.constant.WechatLoginCons;
import com.jd.basic.dto.RegisterDto;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.UserInfo;
import com.jd.basic.utils.*;
import com.jd.system.domain.Log;
import com.jd.system.domain.Menu;
import com.jd.system.mapper.MenuMapper;
import com.jd.system.mapper.PermissionMapper;
import com.jd.system.service.impl.MenuServiceImpl;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.domain.Wxuser;
import com.jd.user.dto.UserLoginDto;
import com.jd.user.dto.WechatBinderDto;
import com.jd.user.dto.WechatDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.mapper.WxuserMapper;
import com.jd.user.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 小林同学
 * @version 1.0
 * @description: TODO
 * @date 2023/3/7 16:09
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtPubKey;

    @Autowired
    private UserMapper userMapper;


    @Override
    public AjaxResult userLogin(UserLoginDto dto) throws Exception {
        // 校验前端参数，已完成
        // 根据账号查询logininfo表里面有没有该对象

        Logininfo logininfo = logininfoMapper.findByUsername(dto);

        // 如果没有该对象或者为null,需要用户先注册
        if (null == logininfo){
            throw new BusinessException("账号或密码错误");
        }
        // 校验输入密码和数据库的密码是否一致
        // 先获取当前对象的盐值
        String salt = logininfo.getSalt();
        String passwordMd = MD5Utils.encrypByMd5(salt + dto.getPassword());
        // 获取当前对象数据库的密码
        String passwordDb = logininfo.getPassword();
        if ( ! passwordDb.equals(passwordMd)){
            throw  new BusinessException("账号或密码错误");
        }
        HashMap<String, Object> map = getMap(logininfo);

        return AjaxResult.me().success(map);
    }

    @Override
    public AjaxResult getWechatToken(WechatDto dto) throws Exception {
        // 校验参数
        // 发送第二次接口请求
        String strJson = HttpUtil.httpGet(String.format(WechatLoginCons.SECOND_REQUEST, WechatLoginCons.APPID, WechatLoginCons.SECRET, dto.getCode()));
        if (StringUtils.isBlank(strJson)){
            throw new BusinessException("微信崩了1");
        }
        JSONObject jsonObject = JSONObject.parseObject(strJson);
        if (null == jsonObject){
            throw new BusinessException("微信崩了2");
        }
        // 根据openid查询t_wxuser表里是否有数据
        String openid = (String) jsonObject.get("openid");
        Wxuser wxuser = wxuserMapper.findByOpenId(openid);
        if (null != wxuser){
            // 如果有数据，直接登陆成功
            Logininfo logininfo = logininfoMapper.findByUserID(wxuser.getUserId());
            HashMap<String, Object> map = getMap(logininfo);
            return AjaxResult.me().success(map);
        } else {
            String accessToken = (String) jsonObject.get("access_token");
            // 非空判断
            if (null == accessToken){
                throw new BusinessException("微信崩了3");
            }
            return AjaxResult.me().fail().setMsg("nobinder").setResultObj("?accessToken="+accessToken+"&openId="+openid);
        }
    }

    @Override
    public AjaxResult binding(WechatBinderDto dto) throws Exception {
        // 校验参数
        // 校验手机验证码是否和redis的一致
        String phoneCodeRedis = (String) redisTemplate.opsForValue().get(String.format(WechatLoginCons.WECHAT_CODE_KEY, dto.getPhone()));
        if (null == phoneCodeRedis || ! phoneCodeRedis.equals(dto.getVerifyCode())) {
            throw new BusinessException("手机验证码错误");
        }
        // 发送第三个接口，通过token和openId获取该用户的信息
        String strJson = HttpUtil.httpGet(String.format(WechatLoginCons.THIRD_REQUEST, dto.getAccessToken(), dto.getOpenId()));
        // 非空判断
        if (StringUtils.isBlank(strJson)){
            throw new BusinessException("微信崩了4");
        }
        // 因为表字段和微信传回来的字段大致相同，使用映射返回wxuser对象，直接映射
        Wxuser wxuser = JSONObject.parseObject(strJson, Wxuser.class);

        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null != user ) {

            // 将userid赋值在该对象wxuser表里的userid字段
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
            logininfo = logininfoMapper.findByUserID(wxuser.getUserId());
        } else {
            // 先添加logininfo表，再是user表，最后是wxuser；
            logininfo = dto.getLogininfo();
            logininfoMapper.add(logininfo);
             user = dto.getUser();
             user.setLogininfoId(logininfo.getId());
             userMapper.add(user);
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
        }
        HashMap<String, Object> map = getMap(logininfo);
        return AjaxResult.me().success(map);
    }


//    private HashMap<String, Object> getMap(Logininfo logininfo) {
//        // 后端生成一个key为token和value为账号信息的map 返回给前端，主要是拦截器校验
//        // 先生成token
//        String token = UUID.randomUUID().toString();
//        // 重置敏感参数
//        logininfo.setEmail(null);
//        logininfo.setPhone(null);
//        logininfo.setSalt(null);
//        // 将token存入redis中
//        redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
//        HashMap<String,Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo", logininfo);
//        return map;
//    }
    private HashMap<String, Object> getMap(Logininfo logininfo) throws Exception {
        HashMap<String,Object> map = new HashMap<>();
       // 获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pri").getFile());
       // 使用私钥生成token
        UserInfo userInfo = new UserInfo();

        userInfo.setLogininfo(logininfo);
        if (0 == logininfo.getType()) {
            List<Menu> menus = menuMapper.findMenuBylogininfoId(logininfo.getId());
            userInfo.setMenus(menus);
            List<String> permissions = permissionMapper.findSNByLogininfoId(logininfo.getId());
            userInfo.setPermissions(permissions);
            map.put("menus", menus);
            map.put("permissions", permissions);
        }
        // 生成token
        String token = JwtUtils.generateTokenExpireInSeconds(userInfo, privateKey, 300000000);
        // 重置敏感参数
        logininfo.setEmail(null);
        logininfo.setPhone(null);
        logininfo.setSalt(null);

        map.put("token",token);
        map.put("logininfo", logininfo);
        return map;


    }
}
